#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年2月28日

@author: chenyongbing
'''
import sys,os
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]


from kafka.consumer import KafkaConsumer
import time,datetime
import sys

from MacData.ttypes import *



import logging,logging.handlers



class ShowRawdataFromKafka(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        
    def get_rawdata_from_kafka_to_file(self,topic='wifisource',broker_list=["localhost:9092"],logfile = 'myapp.log',maxBytes=20*1024*1024,backupCount=0,consumer_group='my_django_consumer_group'):
        

        # Set up a specific logger with our desired output level
        logger = logging.getLogger('MyLogger')
        logger.setLevel(logging.DEBUG)
         
        # Add the log message handler to the logger
        handler = logging.handlers.RotatingFileHandler(logfile, maxBytes=maxBytes, backupCount=backupCount)
        
        handler.setFormatter(logging.Formatter('%(message)s'))
        logger.addHandler(handler)
        kafka = KafkaConsumer(topic,metadata_broker_list=broker_list,group_id=consumer_group,auto_commit_enable=True)
        while 1:
            nextmsg = kafka.next()
            msg = nextmsg.value
            logger.info(msg)
        

            
    
    def get_wifinotification_from_kafka(self,topic='wifinotification',broker_list=["localhost:9092"],consumer_group='django_consumer',logfile = 'myapp.log',maxBytes=20*1024*1024,backupCount=0):
        # Set up a specific logger with our desired output level
        logger = logging.getLogger('MyLogger')
        logger.setLevel(logging.DEBUG)
         
        # Add the log message handler to the logger
        handler = logging.handlers.RotatingFileHandler(logfile, maxBytes=maxBytes, backupCount=backupCount)
        
        handler.setFormatter(logging.Formatter('%(message)s'))
        logger.addHandler(handler)
        kafka = KafkaConsumer(topic,metadata_broker_list=broker_list,group_id=consumer_group,auto_commit_enable=True)
        while 1:
            nextmsg = kafka.next()
            msg = nextmsg.value
            
            mb = TTransport.TMemoryBuffer(msg)
            oprot = TBinaryProtocol.TBinaryProtocol(mb)
            data = MacData()
            data.read(oprot)
            print data
            logger.info(data)
    
            
            
if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('--run',metavar="rawdata or roledata",default='wifisource')
    
    args = parser.parse_args()
    
    runType = args.run
    
    import logging
    from localConfig import myLocalConfig
    
    if runType in myLocalConfig.kafkaConfig.keys():
    
        broker_list = myLocalConfig.kafkaConfig[runType]['broker_list']
        topic = myLocalConfig.kafkaConfig[runType]['topic']
        consumer_group = myLocalConfig.kafkaConfig[runType]['consumer_group']
        
        logfile = myLocalConfig.kafkaConfig[runType]['raw_file']
        maxBytes = myLocalConfig.kafkaConfig[runType]['maxbytes']
        backupCount = myLocalConfig.kafkaConfig[runType]['backupcount']
        myShowRawdataFromKafka = ShowRawdataFromKafka()
        if runType =='rawdata':
            myShowRawdataFromKafka.get_rawdata_from_kafka_to_file(logfile=logfile,
                                                                  topic=topic,
                                                                  broker_list = broker_list,
                                                                  maxBytes=maxBytes,
                                                                  backupCount=backupCount,
                                                                  consumer_group=consumer_group)
        elif runType == 'roledata':
            myShowRawdataFromKafka.get_wifinotification_from_kafka(logfile=logfile,
                                                                   topic=topic,
                                                                   broker_list = broker_list,
                                                                   maxBytes=maxBytes,
                                                                   backupCount=backupCount,
                                                                   consumer_group=consumer_group)